
<template>
  <div class="p-2">
    <el-card shadow="hover">
      <div>
        <h3><span style="font-size: 20px; color: red;"></span></h3>
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="保险公司名称" prop="insuranceCompanyName">
            <el-select v-model="selectedInsurance" placeholder="请选择保险公司名称" clearable>
              <el-option value="" label="不选择"></el-option>
              <el-option v-for="post in insuranceList" :key="post.postId" :value="post.postName" :label="post.postName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="市" prop="city">
            <el-select v-model="selectedCity" placeholder="请选择市" clearable @change="handleCityChange">
              <el-option value="" label="不选择"></el-option>
              <el-option v-for="city in cityOptions" :key="city.id" :value="city.name" :label="city.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="县" prop="districtCounty">
            <el-select v-model="selectedDistrictCounty" placeholder="请选择县" clearable>
              <el-option value="" label="不选择"></el-option>
              <el-option v-for="county in countyOptions" :key="county.id" :value="county.name" :label="county.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="refreshMap">搜索</el-button>
            <el-button type="danger" @click="resetData">刷新</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card shadow="hover" class="map-card">
      <div>
        <a id="back" href="javascript:;" v-show="showBackButton" @click="goBack" class="center-btn">返回</a>
        <div id="main2" style="height: 800px"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { listNyt7PolicyInsurance } from '@/api/Nyt7PolicyInsurance/Nyt7PolicyInsurance/index.ts';
import { listPost } from '@/api/system/post/index'; // 导入 listPost 接口
import { listNyt7RegionManagement } from '@/api/Nyt7RegionManagement/Nyt7RegionManagement'; // 导入区域管理 API

// 布尔类型的响应数据,控制页面返回按钮显示状态
const showBackButton = ref(false);
// 存储初始化得到echarts图
const myChart = ref(null);
// 地图层级
const mapList = ref([]);

// 保险公司列表
const insuranceList = ref([]);
// 选择的保险公司
const selectedInsurance = ref('');

// 存储保单数据
const policyData = ref([]);




// 市县选择
const selectedCity = ref('');
const selectedDistrictCounty = ref('');
const cityOptions = ref([]);
const countyOptions = ref([]);




// 区域管理数据
const regionManagementList = ref([]);




// 获取保单数据
const fetchpolicyData = async () => {
  try {
    const response = await listNyt7PolicyInsurance();
    console.log('Fetch policy Data Response:', response);
    if (!response || response.code !== 200 || !response.rows) {
      throw new Error('Invalid data format, missing rows field');
    }
    // 验证每个地块数据是否包含经纬度字段
    const rows = response.rows;
    if (!Array.isArray(rows) || rows.length === 0) {
      throw new Error('No policy data available');
    }
    rows.forEach(policy => {
      if (!policy.plotDetailInfo.longitude || !policy.plotDetailInfo.latitude) {
        throw new Error(`Plot data missing longitude or latitude: ${JSON.stringify(policy)}`);
      }
    });
    policyData.value = rows;
    console.log('policyData:', policyData.value);
  } catch (error) {
    console.error('获取保单数据失败:', error.message);
    alert('获取保单数据失败，请重试！');
  }
};

// 各省份的数据
const allData = [
  { name: '石家庄市' },
  { name: '保定市' },
  { name: '沧州市' },
  { name: '承德市' },
  { name: '邯郸市' },
  { name: '衡水市' },
  { name: '廊坊市' },
  { name: '秦皇岛市' },
  { name: '唐山市' },
  { name: '邢台市' },
  { name: '张家口市' }
];

// 数据获取与相关逻辑函数
const getJSON = async ({ name }, callback) => {
  console.log('Fetching map data for:', name);
  const url = `/map/${name}.json`;

  //try {
    const response = await fetch(url);
    console.log('Fetch Map Data Response:', response);
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log('Fetch Map Data Data:', data);
    callback(data);
    setBackbtn({ name });

  //}
  // catch (error) {
  //   console.error('获取地图数据失败:', error);
  //   alert('无此区域地图显示，请查看其他区域！');
  // }
};

const setBackbtn = ({ name }) => {
  mapList.value.push({ name });
  showBackButton.value = name !== 'hebei';
  console.log(JSON.stringify(mapList.value));
};

// 返回上一级地图
const goBack = () => {
  if (mapList.value.length >= 2) {
    const { name } = mapList.value[mapList.value.length - 2];
    mapList.value.splice(-2, 2);
    getJSON({ name }, (data) => {
      renderChart(name, data);
      showBackButton.value = mapList.value.length > 0;
    });
  }
};

// 初始化地图函数
const initChinaMap = () => {
  mapList.value = [];
  getJSON({ name: 'hebei' }, (data) => {
    renderChart('hebei', data);
    if (mapList.value.length === 0) {
      showBackButton.value = false;
    }
  });
};



const renderChart = (name, data) => {
  console.log('Rendering chart for:', name);
  console.log('Map data:', data);
  echarts.registerMap(name, data);

  const filteredData = filterPolicyData();
  console.log('Filtered data:', filteredData);
  const markPoint = {
    symbol: 'pin',
    symbolSize: 20,
    label: {
      show: true,
      formatter: function (params) {
        return params.data.name;
      }
    },
    data: filteredData.map(policy => ({
      name: policy.plotDetailInfo.plotCode,
      coord: [parseFloat(policy.plotDetailInfo.longitude), parseFloat(policy.plotDetailInfo.latitude)],
      value: policy.plotDetailInfo.insuredArea
    }))
  };
  setOption(name, allData, markPoint);
};





const filterPolicyData = () => {
  let filteredData = policyData.value;
  if (selectedInsurance.value) {
    filteredData = filteredData.filter(policy => policy.sysPost.postName === selectedInsurance.value);
  }
  if (selectedCity.value) {
    filteredData = filteredData.filter(policy => policy.plotDetailInfo.city === selectedCity.value);
  }
  if (selectedDistrictCounty.value) {
    filteredData = filteredData.filter(policy => policy.plotDetailInfo.districtCounty === selectedDistrictCounty.value);
  }
  return filteredData;
};



const setOption = (name, data, markPoint) => {
  const option = {
    tooltip: {
      show: true,
      formatter: function (params) {
        console.log('params:', params);
        if (params.componentType === 'markPoint') {
          const policyDetailInfo = policyData.value.find(policy => policy.plotDetailInfo.plotCode === params.name);
          console.log('policyDetailInfo:', policyDetailInfo);
          if (policyDetailInfo) {
            return `
              投保人：${policyDetailInfo.farmerInsuranceInfo.farmerName}<br>
              市：${policyDetailInfo.plotDetailInfo.city}<br>
              县：${policyDetailInfo.plotDetailInfo.districtCounty}<br>
              乡：${policyDetailInfo.plotDetailInfo.town}<br>
              村：${policyDetailInfo.plotDetailInfo.village}<br>
              投保总面积：${policyDetailInfo.plotDetailInfo.insuredArea}<br>
              投保总户数：${policyDetailInfo.totalInsuredHouseholds}<br>
              保费总额：${policyDetailInfo.totalPremium}<br>
              用户自缴总额：${policyDetailInfo.totalSelfPaidByUser}<br>
              投保公司：${policyDetailInfo.sysPost.postName}
            `;
          }
        }
        return '';
      }
    },
    visualMap: {
      type: 'continuous',
      text: ['高', '低'],
      showLabel: true,
      left: 'right',
      orient: 'vertical',
      min: 0,
      max: 1200,
      inRange: {
        color: ['#edfbfb', '#b7d6f3', '#40a9ed', '#3598c1', '#215096']
      },
      splitNumber: 0
    },
    series: [{
      name: 'MAP',
      type: 'map',
      mapType: name,
      selectedMode: 'false',
      label: {
        normal: {
          show: true
        },
        emphasis: {
          show: true
        }
      },
      data: data,
      markPoint: markPoint
    }]
  };
  console.log('Option:', option);
  myChart.value.setOption(option, true);
};




// 处理市的选择变化
const handleCityChange = (cityName) => {
  selectedDistrictCounty.value = ''; // 清空县选择
  const selectedCity = cityOptions.value.find(city => city.name === cityName);
  if (selectedCity) {
    countyOptions.value = regionManagementList.value.filter(item => item.pid === selectedCity.id);
    console.log('County Options:', countyOptions.value); // 添加日志输出
  } else {
    countyOptions.value = [];
  }
};




// 重置数据
const resetData = async () => {
  try {
    // 重置选择项
    selectedInsurance.value = '';
    selectedCity.value = '';
    selectedDistrictCounty.value = '';

    // 重新获取保单数据
    await fetchpolicyData();

    // 重新获取区域管理数据
    await getRegionManagementList();
    countyOptions.value = null;
    // 重新初始化地图
    initChinaMap();
  } catch (error) {
    console.error('重置数据失败:', error.message);
    alert('重置数据失败，请重试！');
  }
};



// 搜索后的逻辑
const refreshMap = async () => {
  try {
    await fetchpolicyData();
    const currentMapName = mapList.value[mapList.value.length - 1]?.name || 'hebei';
    getJSON({ name: currentMapName }, (data) => {
      renderChart(currentMapName, data);
    });
  }
  catch (error) {
    console.error('搜索失败:', error.message);
    alert('搜索失败，请重试！');
  }
};




// 获取区域管理数据的方法
const getRegionManagementList = async () => {
  const res = await listNyt7RegionManagement();
  regionManagementList.value = res.data;
  cityOptions.value = regionManagementList.value.filter(item => item.pid === 182754); // 假设parentId为182754的是市
};

onMounted(() => {
  myChart.value = echarts.init(document.getElementById('main2'));
  myChart.value.on('click', (params) => {
    console.log(params);
    if (params.data) {
      const { name, level } = params.data;
      console.log(name, level);
      if (level === 'district') {
        alert('无此区域地图显示！');
        initChinaMap();
        return;
      }
      getJSON({ name }, (data) => {

        echarts.registerMap(name, data);
        let filteredData = filterPolicyData();
        filteredData = filteredData.filter(policy => policy.plotDetailInfo.city === name);
        console.log('Filtered data:', filteredData);
        const markPoint = {
          symbol: 'pin',
          symbolSize: 20,
          label: {
            show: true,
            formatter: function (params) {
              return params.data.name;
            }
          },
          data: filteredData.map(policy => ({
            name: policy.plotDetailInfo.plotCode,
            coord: [parseFloat(policy.plotDetailInfo.longitude), parseFloat(policy.plotDetailInfo.latitude)],
            value: policy.plotDetailInfo.insuredArea
          }))
        };
        setOption(name, allData, markPoint);
      });
    }
  });

  fetchpolicyData().then(() => {
    initChinaMap();
  });

  listPost({}).then(response => {
    if (response.rows && response.rows.length > 0) {
      insuranceList.value = response.rows;
      console.log(response.rows);
    } else {
      console.error('获取保险公司列表失败:', response);
    }
  }).catch(error => {
    console.error('获取保险公司列表失败:', insuranceList.value);
    alert('获取保险公司列表失败，请重试！');
  });

  // 获取区域管理数据
  getRegionManagementList();
});
</script>

<style scoped>
.center-btn {
  display: inline-block;
  background-color: #007bff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  text-decoration: none;
  transition: background-color 0.3s ease;
}

.center-btn:hover {
  background-color: #0056b3;
}

.content {
  display: flex;
  justify-content: space-between;
  width: 100%;
  max-width: 1200px;
}

.select-container {
  display: flex;
  align-items: center;
}

.custom-select {
  position: relative;
  display: inline-block;
  width: 200px;
}

.custom-select select {
  display: inline-block;
  width: 100%;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  background-color: #fff;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 5"><path fill="#333" d="M2 0L0 2h4zm0 5L0 3h4z"/></svg>');
  background-repeat: no-repeat;
  background-position: right 10px center;
  background-size: 10px 10px;
}

.custom-select select:focus {
  border-color: #66afe9;
  outline: none;
}

.insurance-card {
  margin-bottom: 20px;
}

.map-card {
  margin-top: 20px;
}
</style>
